#!/usr/bin/perl
#
# Take a place name as an argument, and display
# interesting information about it.
#
# Uses the places file as a basis, but also the fast-load
# overview created by .....
#
use Counter;
use CounterCGI;
use Fcntl;
use FillForm;
use ErrorForm;
use Counter::CGI;
use UNIVERSAL qw(isa); # to get type-check ability
use CGI::Carp;

require "temp/countrydata.pl";

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
# this shoud retrieve all query information
$q = new Counter::CGI;
@names = $q->keywords();
if ($q->param("place")) {
    @names = $q->param("place");
} else {
    @names = $q->keywords();
    if ($names[0]) {
	warn "Someone using old-style call: ", $q->referer(), "\n";
    }
}
$file = FileTable::open("db/places", O_RONLY);
$persons = FileTable::open("db/persons", O_RONLY);
if ($#names >= 0) {
    $recname = join(" ", @names);
    #warn "Recname is <$recname>\n";
    if ($recname =~ /^\d+$/) {
	$rec = $file->get($recname);
    } else {
	$rec = $file->getbykey(name, $recname);
    }
} else {  #if ($#names < 0)
    # go default: World
    $rec = $file->get(1);
}
if (!$rec) {
    errorForm("Record $recname not found");
}
$recname = $rec->{name};
$within = $file->get($rec->{within}) if $rec->{within};
#
# Show the record
#

print <<EoF;
Content-type: text/html; charset="utf-8"

<html>
EoF
CounterCGI::pagehead("Place information for $$rec{name}");
print "<body bgcolor=white>\n";
CounterCGI::pagetop($q);

print <<EoF;
<h1><img src="/gifs/Logo-small.png" alt="Linux Counter Logo">
Place Information about $$rec{name} $$rec{longname}</h1>
<table border>
EoF
print "<tr><th>Key<th>", $rec->key, "\n";

for $field ($file->fields()) {
    print "<tr><td>$field";
    if ($field eq "contains") {
	print "<td><i>See below</i>\n" if $$rec{$field};
    } elsif ($field eq "userlist") {
	$usercount = $persons->count("placeid = ?", $$rec{name});
	#$usercount = split(" ", $$rec{$field});
	print "<td colspan=2><a href=\"userlist.cgi?", urlquote($$rec{name}),
	"\">List all ",
	$usercount, " users</a>\n";
    } elsif ($field eq "html") {
	print "<td colspan=\"2\">$$rec{$field}\n";
    } else {
	print "<td>$$rec{$field}\n";
    }
    if ($field eq "within") {
	print "<td>", urlname($within), "\n";
    } elsif ($field eq "maintainer") {
	print "<td>";
	for $userid (split(" ", $$rec{$field})) {
	    $pers = $persons->get($userid);
	    if ($pers) {
                my $my_email = $pers->{email};
		#$my_email =~ s/@/&#x40;/g;
		$my_email = CounterCGI::emailCloaking($my_email, 0, '', 1);
		print $pers->{name}, " &lt;", $my_email, "&gt;<br>\n";
		# Next line changed to previous three
		# print $pers->{name}, " &lt;", $pers->{email}, "&gt;<br>\n";
	    } else {
		print "--$userid--<br>";
	    }
	}
    }

}
print "</table>\n";
if ($rec->{type} eq "country" && $rec->{users} > 0) {
    # Find previous and next country in density ranking
    for $x (keys(%$country)) {
	$c = $country->{$x};
	if ($c->{population} > 0) {
	    $c->{density} = $c->{usercount} / $c->{population};
	} 
	# tidying....
	$c->{name} = $x;
    }
    $ix = 1;
    for $x (sort {$country->{$b}->{density} <=> $country->{$a}->{density}}
	    keys(%$country)) {
	$rank2id[$ix] = $country->{$x};
	$rank{$x} = $ix++;
    }
    $myrank = $rank{$rec->{name}};
    $myc = $country->{$rec->{name}};
    printf "$$myc{longname} is no. $myrank in the density statistics, with %5.2f users/Mpop<br>\n",
    $myc->{density};
    if ($myrank > 1) {
	$nextc = $rank2id[$myrank-1];
	$need = int($nextc->{density} * $myc->{population} - $myc->{usercount}) + 1;
	
	print "$$myc{longname} needs $need more users to pass ",
	urlname($nextc), " and become no. ", $myrank-1, "<br>\n";
    }
    if ($rank2id[$myrank+1]) {
	$prevc = $rank2id[$myrank+1];
	$need = int($myc->{density} * $prevc->{population} - $prevc->{usercount}) + 1;
	print urlname($prevc), " needs $need more users to pass ", $myc->{longname}, " and push it to no. ", $myrank+1, "<br>\n";
    }
}
if ($q->remote_user) {
    $key = $rec->key;
    print <<EoF;
<form method="POST" action="showform.cgi">
<input type=hidden name="db" value="db/places">
<input type=hidden name="form" value="wwws/adm/placerec.php">
<input type=hidden name="key" value="$key">

<input type=submit value="Edit this place">
</form>

<form method="POST" action="addform.cgi">
<input type=hidden name="db" value="db/places">
<input type=hidden name="form" value="wwws/adm/placerec.php">
<!-- Values for the new record -->
<input type=hidden name="within" value="$key">
<input type=hidden name="name" value="$recname:xxx">

<input type=submit value="Add subordinate place">
</form>
<a href="http://counter.li.org/reports/place.php?place=$recname">Standard page for this place</a>
EoF
}

# removed: <a href="/adm/lost-people.php3?placeid=$recname">Lost people at "$recname"</a>

# Print list of subsidiary entities
@places = $file->select("within = ?", $rec->key);
if ($#places >= 0) {
    print "<h2>Subordinate entities</h2>\n";
    undef $place;
    # this is a hack to do things the way they were before....
    for $x (@places) {
	$key = $x->key;
	$place{$key} = $x;
	if (!$place{$key} || !$place{$key}{name}) {
	    $place{$key}{name} = "{Deleted}";
	}
    }
    print "<table border>\n";
    print "<tr><th>Key<th>Type";
    if ( $rec->key == 1 ) {
        print "<th>Flag";
    }
    print "<th>Name<th>Longname",
           "<th>Listed<th>Within\n";
    for $key (sort {
	$place{$b}{type} cmp $place{$a}{type} ||
	"\L$place{$a}{name}" cmp "\L$place{$b}{name}"} keys(%place)) {
	print "<tr>";
	$subrec = $place{$key};
	print "<td>$key<td>$subrec->{type}";
        if ( $rec->key == 1 ) {
	    $flag = $subrec->{name};
	    $flag =~ tr/A-Z/a-z/;
	    if (-r "www/gifs/flags/" . $flag . ".png") {
	        print "<td><img src=\"/gifs/flags/" . $flag . ".png\">";
            } else {
                print "<td><img src=\"/gifs/flags/unknown.png\">";
            }
        }
	print "<td>$subrec->{name} ";
	print "<td>", urlname($subrec);
	#$usercount = split(" ", $subrec->{userlist});
	$usercount = $persons->count("placeid = ?", $$subrec{name});
	if ($usercount > 0) {
	    print "<td> $usercount";
	} else {
	    print "<td> none";
	}
	print "<td>$subrec->{users}";
	if ($q->remote_user && $usercount <= 1) {
	    # wishing for a delete button here.....but forms break up
        }
	print "<br>\n";
    }
    print "</table>\n";
} else {
    print "No subordinates listed\n";
    if ($q->remote_user) {
	$key = $rec->key;
	print <<EoF;
<form method="POST" action="deleteplace.cgi">
<input type=hidden name="key" value="$key">
<input type=submit value="Delete this place">
</form>
EoF
    }
}

print <<EoF;
<hr>
Contact: <a href="mailto:webmaster&#x40;counter.li.org">Webmaster&#x40;counter.li.org</a>
<br>
</body>
</html>
EoF

sub urlname {
# return a string containing an URL to show a place
    my $rec = shift;
    my $str;

    my $longname = $rec->{longname};
    $longname = "<i>nameless</i>" if !$longname;
    if (isa($rec, "FileTable::Record")) {
	$str = sprintf("<a href=\"place.cgi?place=%s\">%s</a>",
		       $rec->key, $longname);
    } else {
	my $name = urlquote($rec->{name});
	$str = sprintf("<a href=\"place.cgi?place=%s\">%s</a>",
                   $name, $longname);
    }
}

